package thread.ProductConsumer;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Producer implements Runnable{

	private volatile boolean isRunning = true;
	private BlockingQueue<PcData> queue; //声明一个队列用于充当内存缓存区
	private static AtomicInteger count = new AtomicInteger();//总数 原子操作
	private static final int SLEEPTIME = 1000;
	
	public Producer(BlockingQueue<PcData> queue){
		this.queue = queue;
	}
	@Override
	public void run() {
		PcData data = null;
		
		Random r = new Random();
		System.out.print("start producer id=" + Thread.currentThread().getId());
		try {
			while(isRunning){
				Thread.sleep(r.nextInt(SLEEPTIME));
				data = new PcData(count.incrementAndGet());//
				System.out.println(data + " is put into queue");
				if(!queue.offer(data,2,TimeUnit.SECONDS)){//提交数据到缓存区中
					System.out.println("falie into queue" + data);
				}
			}
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}

	public void stop(){
		isRunning = false;
	}
}
